package com.zhentao.controller;

import com.alibaba.fastjson2.JSONObject;

import com.zhentao.service.WxService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @author tianshuaifei
 * @data 2024/7/8 11:17
 */

@RestController
public class WxGetQRCodeController {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    WxService wxService;


    @PostMapping("/getQRCode")
    public String getWechatQrcodeByRestTemplate(@RequestBody Map<String, Object> body) {
        // 假设'scene'是包含需要编码的值的键
        String sceneKey = "scene";
        if (body.containsKey(sceneKey)) {
            String sceneValue = body.get(sceneKey).toString();
            // 对scene参数进行Base64编码
            String encodedScene = Base64.getUrlEncoder().encodeToString(sceneValue.getBytes(StandardCharsets.UTF_8));
            // 将编码后的值放回body
            body.put(sceneKey, encodedScene);
        }
        System.out.println(body);
        // 以下是获取access_token和调用微信API的代码，省略...
        String accessToken = wxService.getAccessToken();
        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=%s";
        String accessUrl = String.format(url, accessToken);

        // 使用编码后的body发送请求
        String qRstr = Base64.getEncoder().encodeToString(restTemplate.exchange(accessUrl, HttpMethod.POST, new HttpEntity<>(body, null), byte[].class).getBody());
        return qRstr;
    }


}
